package org.example.gateway;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.oauth2.jwt.JwtException;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

@Component
public class AuthFilter implements GlobalFilter, Ordered {


    private PublicKey publicKey;

    @Autowired
    public AuthFilter(@Value("${jwt.public.key}") String publicKeyStr) throws Exception {
        this.publicKey = loadRSAPublicKey(publicKeyStr);
    }
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String jwt = exchange.getRequest().getHeaders().getFirst("Authorization");

//        if (jwt == null || !isTokenValid(jwt)) {
//            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
//            return exchange.getResponse().setComplete();
//        }

        if (jwt != null && jwt.startsWith("Bearer ")) {
            jwt = jwt.substring(7);
            try {
                Claims claims = Jwts.parser()
                        .verifyWith(publicKey)
                        .build()
                        .parseSignedClaims(jwt).getPayload();

                // 在这里，你可以从claims中获取用户信息，并设置到安全上下文中
                // 例如：SecurityContextHolder.getContext().setAuthentication(...)

                // 如果Token有效，继续执行下一个Filter
                return chain.filter(exchange);
            } catch (JwtException e) {
                // 如果Token无效，则返回错误信息
                ServerHttpResponse response = exchange.getResponse();
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
        }

        return chain.filter(exchange);
    }

//    private boolean isTokenValid(String token) {
//        // 实现你的token验证逻辑
//        // 例如，可以与数据库中的token比对，或者调用安全服务
//        return "expected-token-value".equals(token);
//        RSATokenValidator.verifyRSA()
//    }

    @Override
    public int getOrder() {
        // 确保此过滤器在其他过滤器之前运行
        return -1;
    }

    public PublicKey loadRSAPublicKey(String publicKeyStr) throws Exception {
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyStr));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(keySpec);
    }
}